package com.etop.jansing.dao;

import com.etop.jansing.entities.BaseEntity;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.data.repository.NoRepositoryBean;

import javax.annotation.Resource;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.Date;

/**
 * Created by jansing on 2015/10/18.
 */
@SuppressWarnings("uncheck")
@NoRepositoryBean
public class BaseDao<T extends BaseEntity> {
    @Resource
    private SessionFactory sessionFactory;

    private Class<T> persistentClass;

    protected Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    public BaseDao() {
        persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    public Serializable save(T t) {
        Session session = getSession();
        return session.save(t);
    }

    public void update(T t) {
        t.setUpdateDate(new Date());
        Session session = getSession();
        session.update(t);
    }

    public void delete(T t) {
        Session session = getSession();
        t.setValid(false);
        session.update(t);
    }

    public T get(long id) {
        Session session = getSession();
        T t = (T) session.get(persistentClass, id);
        if (t != null && !t.getValid()) {
            t = null;
        }
        return t;
    }
}
